import re

from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from station.models import Station


class StationSerializer(serializers.ModelSerializer):

    users = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    station_name = serializers.CharField(label="站点名", required=True, error_messages={"blank": "站点名不能为空", "required": "站点名不能为空"})
    procurator = serializers.CharField(label="代理人", required=True, error_messages={"blank": "代理人不能为空", "required": "代理人不能为空"})
    id_card = serializers.CharField(label="身份证号", required=True, write_only=True, error_messages={"blank": "身份证号不能为空", "required": "身份证号不能为空"})
    phone = serializers.CharField(label="手机号", required=True, error_messages={"blank": "手机号不能为空", "required": "手机号不能为空"})
    address = serializers.CharField(label="详细地址", required=True, error_messages={"blank": "详细地址不能为空", "required": "详细地址不能为空"})
    longitude = serializers.DecimalField(label="经度", max_digits=10, decimal_places=7, error_messages={"blank": "经度不能为空"})
    latitude = serializers.DecimalField(label="纬度", max_digits=10, decimal_places=7, error_messages={"blank": "经度不能为空"})
    permit_img = serializers.ImageField(label='营业执照', write_only=True)

    def validate(self, attrs):
        id_card = attrs.get("id_card")
        phone = attrs.get("phone")
        address = attrs.get("address")
        users = attrs.get("users")

        stations = Station.objects.filter(users=users.pk)
        if len(stations) != 0:
            raise serializers.ValidationError("您已注册了商家")
        if not re.match("^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$", id_card):
            raise serializers.ValidationError("身份证号码非法")
        if not re.match("^1[358]\d{9}$|^147\d{8}$|^176\d{8}$", phone):
            raise serializers.ValidationError("手机号非法")
        # if not re.match("^(\w+市\w+(区|县)\w+镇\w+街\d+号)|(\w+市\w+(区|县)\w+街\d+号)|(\w+市\w+(区|县)\w+(乡|村)\d+号)$", address):
        #     raise serializers.ValidationError("地址格式不正确(xx市xx区/县/镇/乡/村xx街xx号)")

        return attrs

    def is_valid(self, raise_exception=False):
        try:
            super().is_valid(raise_exception=True)
        except Exception as e:
            assert isinstance(e, ValidationError)
            for k, v in e.detail.items():
                raise ValidationError({"err_msg": v[0]})

    class Meta:
        model = Station
        fields = "__all__"

